import { BASE_URL_SETTING } from './env.setting';
import { Response } from './utils/request';

// app.ts
App<IAppOption>({
  globalData: {
    appId: undefined,
    openId: undefined,
    env: undefined, // 运行环境
    baseUrl: undefined, // 基础路径
    pageData: undefined
  },
  setEnv() {
    const accountInfo = wx.getAccountInfoSync();
    const { appId, envVersion } = accountInfo.miniProgram;
    this.globalData.appId = appId;
    this.globalData.env = envVersion;
    this.globalData.baseUrl = BASE_URL_SETTING[envVersion];
  },
  getOpenId(code: string) {
    return new Promise((resolve, reject) => {
      wx.request<Response<string>>({
        url: this.globalData.baseUrl + '/mini-app/getOpenId?code=' + code,
        method: 'GET',
        success: (res) => {
          resolve(res.data.data);
        },
        fail: (err) => {
          reject(err.errMsg);
        }
      });
    });
  },
  getCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          resolve(res.code);
        },
        fail: (err) => {
          reject(err.errMsg);
        }
      });
    });
  },
  async authen() {
    try {
      const code = await this.getCode();
      const openId = await this.getOpenId(code);
      
      this.globalData.openId = openId;

      wx.setStorage({
        key: 'openId',
        data: openId
      });
    } catch (err) {
      wx.showToast({
        icon: 'error',
        title: '获取用户openId失败'
      });
    }
  },
  async onLaunch() {
    this.setEnv();

    const openId = wx.getStorageSync('openId');
    if (!openId) {    
      this.authen();
    } else {
      this.globalData.openId = openId;
    }
  }
});
